package com.lyhlmj.oop_client.Utils;

import com.lyhlmj.oop_client.Frames.PlayFrame.Panels.ChessBoardPanel;

public class ChessUtils {
    //  判断是否有人获胜游戏结束
    public static boolean checkWin(int[][] allChess, int xx, int yy) {
        boolean flag = false;
        int count = 1;
        int color = allChess[xx][yy];
        //  判断是否有五子相连
        count = checkCount(allChess, 1, 0, color, xx, yy); //  横向判断
        if (count >= 5) {
            flag = true;
        } else {
            count = checkCount(allChess,0, 1, color, xx, yy); //  纵向判断
            if (count >= 5) {
                flag = true;
            } else {
                //  判断左下，右上方向
                count = checkCount(allChess,1, -1, color, xx, yy);
                if (count >= 5) {
                    flag = true;
                } else {
                    //  判断右下、左上方向
                    count = checkCount(allChess,1, 1, color, xx, yy);
                    if (count >= 5) {
                        flag = true;
                    }
                }
            }
        }
        return flag;
    }

    private static int checkCount(int[][] allChess, int xChange, int yChange, int color, int xx, int yy) {
        //  计数
        int count = 1;
        //  保存xChange与yChange坐标
        int tempX = xChange;
        int tempY = yChange;
        while ((xx + xChange >= 0 && xx + xChange <= 14 && yy + yChange >= 0 && yy + yChange <= 14) && color == allChess[xx + xChange][yy + yChange] && color != 0) {
            count++;
            if (xChange != 0) {
                xChange++;
            }
            //  y有正负值两种情况
            if (yChange != 0) {
                if (yChange > 0) {
                    yChange++;
                } else {
                    yChange--;
                }
            }
        }
        //  恢复初始状态，判断其他方向
        xChange = tempX;
        yChange = tempY;
        while ((xx - xChange >= 0 && xx - xChange <= 14 && yy - yChange >= 0 && yy - yChange <= 14) && color == allChess[xx - xChange][yy - yChange] && color != 0) {
            count++;
            if (xChange != 0) {
                xChange++;
            }
            //  y有正负值两种情况
            if (yChange != 0) {
                if (yChange > 0) {
                    yChange++;
                } else {
                    yChange--;
                }
            }
        }
        return count;
    }
}
